<?php
/**
 * Created by PhpStorm.
 * User: Xavier
 * Date: 12/27/13
 * Time: 5:28 PM
 */
/*
 * Plugin Name: XH Options
 * Plugin URI: http://xavierh.com
 * Description: Options for a theme
 * Version: 1.0
 * Author: Xavier Huynh
 * Author URI: http://xavierh.com
 */
add_filter('the_content',function($content){
    $id = the_id();
    if(!is_singular('post')){
        return $content;
    }
    $terms = get_the_terms($id,'category');
    $cats = array();

    foreach($terms as $term){
        $cats[] = $term->cat_ID;
    }

    $loop = new WP_Query(
        array(
            'posts_per_page'=>3,
            'category__in'=>$cats,
            'orderby'=>'rand',
            'post__not_in'=>array($id)
        )
    );

    if($loop->have_posts()){
        $content .= '
            <h2>You Also Might Like... </h2>
            <ul class="related-category-posts">
        ';
        while($loop->have_posts()){
            $loop->the_post();

            $content .= '
                <li>
                    <a href="'.get_permalink().'">'.get_the_title().'</a>
                </li>
            ';
        }

        $content .= '</ul>';
        wp_reset_query();
    }
});